package com.itheima.controller;

import com.itheima.aspect.Log;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/emps")
@Slf4j
public class EmpController {

    @Autowired
    EmpService empService;


    //条件分页查询
    //注意@DateTimeFormat。不然格式是yyyy/MM/dd
    @GetMapping
    public Result pageQuery(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer pageSize,
                            String name, Short gender,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        //记录日志
        log.info("分页查询，参数：{},{},{},{},{},{}", page, pageSize, name, gender, begin, end);
        //调用业务层分页查询功能
        PageBean pageBean = empService.pageQuery(page, pageSize, name, gender, begin, end);
        //响应
        return Result.ok(pageBean);
    }


    /*
        批量删除员工
    */
    @Log
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除员工，被删除的员工ids:{}", ids);
        empService.delete(ids);
        return Result.ok();
    }


    @Log
    //新增员工信息
    @PostMapping
    public Result save(@RequestBody Emp emp) {
        //记录日志
        log.info("新增员工, emp:{}", emp);
        //调用业务层新增功能
        empService.save(emp);
        //响应
        return Result.ok();
    }

    //根据id查询员工信息
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询员工信息:{}", id);
        Emp emp = empService.geById(id);
        return Result.ok(emp);
    }

    @Log
    //根据id，修改员工信息
    //不加@RequestBody，emp中将没有数据
    @PutMapping
    public Result updateById(@RequestBody Emp emp){
        log.info("根据id修改员工信息:{}",emp);
        empService.updateById(emp);
        return Result.ok();
    }

}
